import 'package:flutter/material.dart';
import 'dart:async';

class AutoScrollWidget extends StatefulWidget {
  final Widget child;
  final Duration scrollInterval;
  final double scrollOffset;

  const AutoScrollWidget({
    super.key,
    required this.child,
    this.scrollInterval = const Duration(seconds: 2),
    this.scrollOffset = 20.0, // 每次滚动的像素距离，大约一行的高度
  });

  @override
  State<AutoScrollWidget> createState() => _AutoScrollWidgetState();
}

class _AutoScrollWidgetState extends State<AutoScrollWidget> {
  late ScrollController _scrollController;
  Timer? _scrollTimer;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _startAutoScroll();
  }

  @override
  void dispose() {
    _scrollTimer?.cancel();
    _scrollController.dispose();
    super.dispose();
  }

  void _startAutoScroll() {
    _scrollTimer = Timer.periodic(widget.scrollInterval, (timer) {
      if (_scrollController.hasClients) {
        final maxScrollExtent = _scrollController.position.maxScrollExtent;
        final currentScrollPosition = _scrollController.position.pixels;
        
        if (currentScrollPosition >= maxScrollExtent) {
          // 滚动到底部时，回到顶部
          _scrollController.animateTo(
            0,
            duration: const Duration(milliseconds: 500),
            curve: Curves.easeInOut,
          );
        } else {
          // 向上滚动一行
          _scrollController.animateTo(
            currentScrollPosition + widget.scrollOffset,
            duration: const Duration(milliseconds: 500),
            curve: Curves.easeInOut,
          );
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      controller: _scrollController,
      child: widget.child,
    );
  }
}